package com.yzr.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeUnit;

/**
 * @description
 * @author: yzr
 * @date: 2021/10/26 16:06
 **/
@Slf4j
@WebFilter(urlPatterns = "/**", filterName = "myFilter")
@Configuration
public class BaseFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("utf-8");

        String path = request.getRequestURI();
        Instant start = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
        filterChain.doFilter(servletRequest, servletResponse);
        Instant end = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
        log.debug(path + " " + Duration.between(start, end).toMillis() + "ms");
    }
}
